/*******************************************************************************
 * Copyright (c) 2007 University of Oslo.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     University of Oslo - initial API and implementation
 *******************************************************************************/

package com.cea.papyrus.diagram.sequence.sedi.edit.handlers;

import static com.cea.papyrus.diagram.sequence.sedi.model.util.ModelUtil.getCovereds;
import static java.lang.Math.max;

import java.util.List;

import org.eclipse.uml2.uml.Lifeline;
import org.eclipse.uml2.uml.Message;
import org.eclipse.uml2.uml.MessageEnd;
import org.eclipse.uml2.uml.MessageOccurrenceSpecification;

import com.cea.papyrus.diagraminterchange2.di2.GraphNode;

/**
 * @author frankd@ifi.uio.no
 */
public class LifelineLinkHandler {
    public String selectAnchor(GraphNode node, MessageEnd event) {
        // TODO Improve algorithm
        Message message = event.getMessage();
        if (message == null)
            return "A1";

        int position =
                max(getEventPosition(message.getSendEvent()), getEventPosition(message
                        .getReceiveEvent()));
        return "A" + (1 + (position * 2));
    }

    private int getEventPosition(MessageEnd event) {
        int eventPosition = 0;
        if (event instanceof MessageOccurrenceSpecification) {
            MessageOccurrenceSpecification occSpec = (MessageOccurrenceSpecification) event;
            List<Lifeline> covereds = getCovereds(occSpec);
            if (!covereds.isEmpty()) {
                Lifeline covered = covereds.get(0);
                eventPosition = covered.getCoveredBys().indexOf(occSpec);
            }
        }
        return eventPosition;
    }
}
